<?php


namespace App\Service\Workflow\Web;


use App\Enums\OpenShop\InvestmentPromotion\OrganizationManageEnum;
use App\Enums\Workflow\WorkflowV2Enum;
use App\Exceptions\Custom\CustomException;
use App\Models\Guanyuan\GuanyuanSyncShopListModel;
use App\Models\Workflow\WorkflowV2OrderLogModel;
use App\Models\Workflow\WorkflowV2OrderModel;
use App\Models\Workflow\WorkflowV2OrderNodeHandlerModel;
use App\Models\Workflow\WorkflowV2OrderNodeModel;
use App\Remote\Rms\RmsUserRemote;
use App\Service\BaseService;
use App\Service\Cruise\CruiseTemplate\CruiseTemplateService;
use App\Service\Cruise\Mission\WorkflowV2InputService;
use App\Service\OpenShop\Feishu\OrganizationManageService;
use Carbon\Carbon;

class WorkflowV2OrderService extends BaseService
{
    public static function list(
        int $pageSize,
        int $pageNum,
        array $shopIds = [],
        string $dimCode = null,
        string $workflowNo = null,
        int $status = null,
        int $currentHandlerUserid = null,
        int $typeId = null,
        int $createdAtStart = null,
        int $createdAtEnd = null,
        int $updatedAtStart = null,
        int $updatedAtEnd = null
    ): array {
        $paginate = WorkflowV2OrderModel::query()
                                        ->with(['shopRel', 'workFlowV2TypeRel'])
                                        ->when($shopIds, function ($query) use ($shopIds) {
                                            $query->whereIn('shopId', array_unique($shopIds));
                                        })
                                        ->when($dimCode, function ($query) use ($dimCode) {
                                            $query->whereHas('shopRel', function ($_query) use ($dimCode) {
                                                $_query->where('shopId', $dimCode)
                                                       ->orWhere('name', 'like', "%$dimCode%");
                                            });
                                        })
                                        ->when($workflowNo, function ($query) use ($workflowNo) {
                                            $query->where('workflowNo', $workflowNo);
                                        })
                                        ->when(isset($status), function ($query) use ($status) {
                                            $query->where('status', $status);
                                        })
                                        ->when($currentHandlerUserid, function ($query) use ($currentHandlerUserid) {
                                            $query->where('updatedByUid', $currentHandlerUserid);//todo 可能不会更新，要确认一下
                                        })
                                        ->when($typeId, function ($query) use ($typeId) {
                                            $query->where('workflowType2', $typeId);
                                        })
                                        ->when($createdAtStart && $createdAtEnd,
                                            function ($query) use ($createdAtStart, $createdAtEnd) {
                                                $query->where('createdAt', '>=', $createdAtStart);
                                                $query->where('createdAt', '<=', $createdAtEnd);
                                            })
                                        ->when($updatedAtStart && $updatedAtEnd,
                                            function ($query) use ($updatedAtStart, $updatedAtEnd) {
                                                $query->where('updatedAt', '>=', $updatedAtStart);
                                                $query->where('updatedAt', '<=', $updatedAtEnd);
                                            })
                                        ->paginate($pageSize, ['*'], ['page'], $pageNum);

        $userIds = collect($paginate->items())->pluck('createdByUid')->unique()->values()->toArray();
        $users   = $userIds
            ? array_column(RmsUserRemote::getRmsUserByIds($userIds, ['id', 'username']), null, 'id')
            : [];

        return self::pageLists($paginate, function ($item) use ($users) {
            $shopInfo = vsprintf("%s %s", [
                $item->shopRel->shopCode,
                $item->shopRel->name
            ]);

            /** @var Carbon $updatedAt */
            $updatedAt = $item->updatedAt;
            return [
                'id'                     => $item->id,
                'status'                 => $item->status,
                'shopInfo'               => $shopInfo,
                'workflowNo'             => $item->workflowNo,
                'name'                   => $item->name,
                'type2Name'              => $item->workFlowV2TypeRel->name,
                'createdUserName'        => $users[$item->createdByUid]['username'] ?? '-',//'张庆',
                'currentHandlerUserName' => attributeGet($item, "updatedByUidRel.name", "-"),//'夏目 (张永康)',
                'updatedAt'              => $updatedAt->format('Y-m-d H:i'),
                'canApproval'            => $item->canApproval(),//
            ];
        });
    }

    public static function detail(int $id, int $userId): array
    {
        $order = WorkflowV2OrderModel::query()
                                     ->with('currentNodeRel', function ($query) {
                                         $query->with('childrenRel');
                                     })
                                     ->with(['nodesRel', 'currentNodeHandler'])
                                     ->with('shopRel', function ($query) {
                                         $query->with('councilorRel');
                                     })
                                     ->where('id', $id)
                                     ->first();
        if (empty($order)) {
            throw new CustomException('异常工单');
        }

        $shop         = $order->shopRel;
        $councilorRel = $shop->councilorRel;
        $councilor    = vsprintf("%s (%s) -%s", [
            $councilorRel->name,
            $councilorRel->nickname,
            $councilorRel->mobile,
        ]);

        $users = array_column(
            RmsUserRemote::getRmsUserByIds([$order->createdByUid], ['id', 'username', 'mobile']),
            null, 'id'
        );

        $submitComponent = [];
        //找到当前节点,判断当前节点是否有子节点，根据子节点判断是否是当前执行人
        $childrenRel = $order->currentNodeRel->childrenRel;
        if ($order->status === WorkflowV2OrderModel::STATUS_ING
            && $order->currentNodeRel->cruiseOrderId) {
            $childrenNodeIds = collect($childrenRel)->pluck('id')->toArray();
            $canHandler      = collect($order->currentNodeHandler)
                ->when($childrenNodeIds, function ($q) use ($childrenNodeIds) {
                    $q->whereIn('workflowOrderNodeId', $childrenNodeIds);
                })
                ->where('handlerUid', $userId)
                ->where('handlerStatus', WorkflowV2OrderNodeHandlerModel::HANDLER_STATUS_WAIT)
                ->whereIn('handlerType', WorkflowV2Enum::BACK_APPROVAL_TYPE_MAP)
                ->first();
            if ($canHandler) {
                $input           = (new WorkflowV2InputService($order->currentNodeRel->cruiseOrderId, $userId));
                $submitComponent = $input->getInputObjectFill();
            }

            if (isTest() && !$canHandler) {
                $input           = (new WorkflowV2InputService($order->currentNodeRel->cruiseOrderId, $userId));
                $submitComponent = $input->getInputObjectFill();
            }
        }

        $approvalHistory = [];
        $logs            = WorkflowV2OrderLogModel::query()
                                                  ->with('workflowOrderNodeRel')
                                                  ->where('workflowOrderId', $order->id)
                                                  ->where('status', WorkflowV2OrderLogModel::STATUS_FINISH)
                                                  ->get();
        foreach ($logs as $log) {
            $approvalHistoryItem = [
                'info'=> [
                    'nodeName'    => $log->nodeName,
                    'handlerName' => $log->handlerName,
                    'audit'       => $log->audit,
                    'updatedAt'   => $log->updatedAt->format('Y-m-d H:i:s')
                ],
                'submitInfo'=> $log->workflowOrderNodeRel->cruiseOrderId > 0
                    ?  (new WorkflowV2InputService($order->currentNodeRel->cruiseOrderId, 0))
                        ->getInputObjectFill()
                    : []
            ];
            array_push($approvalHistory,$approvalHistoryItem);
        }

        //省区负责人
        $manager = OrganizationManageService::getOrganizationInfoByType(
            OrganizationManageEnum::TYPE_BRANCH_OFFICE,
            $shop->province
        );

        $gyShop          = GuanyuanSyncShopListModel::query()
                                                    ->where('shopId', $shop->id)
                                                    ->first();
        $businessStartAt = '';
        if (optional($gyShop)->openBusinessDate) {
            $carbonDate      = Carbon::parse($gyShop->openBusinessDate);
            $businessStartAt = vsprintf("%s 已开业%s月%s天", [
                $carbonDate->format("Y-m-d"),
                $carbonDate->diffInMonths(Carbon::now()),
                $carbonDate->format('d'),
            ]);
        }

        return [
            'baseInfo'          => [
                'orderInfo' => [
                    'workflowNo'             => $order->workflowNo,//编号
                    'typeName'               => $order->name,//类型
                    'createdUserName'        => $users[$order->createdAtByUid]['username'] ?? '',//提交人
                    'createdUserMobile'      => $users[$order->createdAtByUid]['mobile'] ?? null,//提交人电话
                    'createdAt'              => $order->createdAt->format('Y-m-d H:i'),
                    'currentHandlerUserName' => attributeGet($order, "updatedByUidRel.name", "-"),
                    'updatedAt'              => $order->updatedAt->format('Y-m-d H:i'),
                ],
                'shopInfo'  => [
                    'shopName'        => $shop->name,
                    'businessStartAt' => $businessStartAt,//开业时间
                    'branch'          => $shop->branch,//所属分公司
                    'addressPrefix'   => $shop->addressPrefix,//门店区域
                    'address'         => $shop->address,//门店地址
                    'shopContact'     => $shop->shopContact,//门店联系人
                    'shopMobile'      => $shop->shopMobile,//门店联系方式
                    'councilor'       => $councilor,//督导
                    'branchManager'   => $manager['operationName'] ?? '',//省区负责人
                ],
            ],
            'workflowComponent' => (new WorkflowV2InputService($order->submitCruiseOrderId,
                $userId))->getInputObjectFill(),
            'submitComponent'   => $submitComponent,
            'approvalHistory'   => $approvalHistory,
            'canClose'          => self::canClose($order, $userId) ? 1 : 0,
        ];
    }

    public static function closeOrder(int $orderId, int $userId): void
    {
        $order = WorkflowV2OrderModel::query()
                                     ->with('currentNodeHandler')
                                     ->where('id', $orderId)
                                     ->first();
        if (empty($order)) {
            throw new CustomException('工单异常');
        }
        if (self::canClose($order, $userId)) {
            throw new CustomException('您不可操作');
        }
        $order->status = WorkflowV2OrderModel::STATUS_CLOSE;
        $order->save();
        //todo log
    }


    public static function canClose($order, $userId): bool
    {
        return (bool)collect($order->currentNodeHandler)->where('handlerUid', $userId)->first();
    }


}